﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

using MicroMq.Helper;

using Microsoft.Extensions.DependencyInjection;

namespace MicroMq.Services
{
    class DispatchWorkService
    {
        private readonly Dictionary<string, Cron> dispatchers = new Dictionary<string, Cron>();

        private readonly Timer timer;

        private readonly IServiceProvider serviceProvider;
        public DispatchWorkService(IServiceProvider serviceProvider)
        {
            this.timer = new Timer(TimerCallback, this, 1000, 1000);
            this.serviceProvider = serviceProvider;
        }

        public void Enqueue(string taskName, string cronExpression)
        {
            dispatchers[taskName] = new Cron(cronExpression);
        }

        public void Dequeue(string taskName)
        {
            dispatchers.Remove(taskName);
        }

        private void TimerCallback(object obj)
        {
            var manager = serviceProvider.GetService<MqConnectionManager>();
            var now = DateTimeOffset.Now;
            foreach ((var taskName, var cron) in dispatchers)
            {
                if (cron.IsSatisfiedBy(now))
                {
                    Execute(manager, taskName);
                }
            }
        }

        public void Execute(MqConnectionManager manager, string taskName)
        {
            var session = manager.Group(taskName);
            if (!session.Has()) return;

            var buffer = ByteWriteBuffer.Alloc()
              .WriteUnknownString(taskName)
              .ToBytes();
            session.SendAsync(buffer);
        }
    }
}
